package prj.carmap.mobile.process;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;

import prj.carmap.mobile.CarmapApplication;
import prj.carmap.mobile.R;
import prj.carmap.mobile.util.FileUtil;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.widget.RemoteViews;

/**
 * 版本更新服务
 */
public class DownLoadService extends Service {

	static final String TAG = "DownLoadService";

	private final static String FILE_NAME = "carmap.apk";

	private int NOTIFICATION_ID = 110;
	private NotificationManager notificationManager = null;
	private FileUtil fileUtil = FileUtil.INSTANCE;

	@Override
	public void onCreate() {
		notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

		super.onCreate();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		System.out.println(TAG + " onStartCommand() ");
		new DownloadAttachmentTask().execute(intent.getStringExtra("url"));
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	public Notification CreateNotification(String AttachmentName, int notification_id) {
		Notification notification = new Notification(R.drawable.download,
				getString(R.string.download_dialog_start),
				System.currentTimeMillis());

		notification.contentView = new RemoteViews(getApplication().getPackageName(), R.layout.download_dialog);

		notification.contentView.setProgressBar(R.id.download_dialog_pb, 100, 0, false);
		notification.contentView.setTextViewText(R.id.download_dialog_tv, getString(R.string.download_dialog_start));
		notification.contentView.setTextViewText(R.id.download_dialog_filename, AttachmentName);

		notification.contentIntent = PendingIntent.getActivity(this, 0, new Intent(), 0);

		// Intent intent = new Intent(this,DownloadManagerActivity.class);
		// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
		// notification.contentIntent = PendingIntent.getActivity(this, 0,
		// intent, 0);

		notification.flags = Notification.FLAG_NO_CLEAR;

		notificationManager.notify(notification_id, notification);

		return notification;
	}

	public void UpdateNotification(int id, Notification notification, int progress, String AttachmentName) {
		if (progress < 0)
		{
			notification.flags = Notification.FLAG_AUTO_CANCEL;
			notification.contentView.setProgressBar(R.id.download_dialog_pb, 100, 0, false);
			notification.contentView.setTextViewText(R.id.download_dialog_tv, getString(R.string.download_dialog_failed));
		}
		else if (progress >= 100)
		{
			notification.flags = Notification.FLAG_AUTO_CANCEL;
			notification.contentView.setProgressBar(R.id.download_dialog_pb, 100, progress, false);
			notification.contentView.setTextViewText(R.id.download_dialog_tv, getString(R.string.download_dialog_end));

			notification.contentIntent = PendingIntent.getActivity(this, 0, fileUtil.GetOpenFileTypeIntent(AttachmentName), 0);
		}
		else
		{
			notification.contentView.setProgressBar(R.id.download_dialog_pb, 100, progress, false);
			notification.contentView.setTextViewText(R.id.download_dialog_tv, getString(R.string.download_dialog_already) + progress + "%");
		}

		notificationManager.notify(id, notification);
	}

	public void failed(int id, Notification notification) {
		// notification.contentView.setProgressBar(R.id.download_dialog_pb, 100, 0, false);
		notification.contentView.setTextViewText(R.id.download_dialog_tv, getString(R.string.download_dialog_failed));
		notification.flags = Notification.FLAG_AUTO_CANCEL;

		notificationManager.notify(id, notification);
	}

	private class DownloadAttachmentTask extends AsyncTask<String, Integer, Integer> {

		private Notification notification = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

			notification = CreateNotification(
					getApplication().getString(R.string.app_name) + "新版",
					NOTIFICATION_ID);
		}

		@Override
		protected Integer doInBackground(String... params) {
			InputStream inputStream = null;
			RandomAccessFile randomAccessFile = null;

			try {
				// 下载地址
				String urlString = CarmapApplication.SERVER_URL + params[0];
				System.out.println(TAG + urlString);
				if (!fileUtil.SdcardExist()) {
					failed(NOTIFICATION_ID, notification);
					return FileUtil.DOWNLOAD_FAILED;
				}

				// 创建，打开文件
				File file = new File(FileUtil.sdcard_dir + "/" + FILE_NAME);
				if (file.isFile() && file.exists()) {
					file.delete();
				}
				randomAccessFile = new RandomAccessFile(file, "rwd");
				// 获得一个连接 ，并且把下载地址中的中文字符进行编码
				HttpURLConnection connection = (HttpURLConnection) new URL(urlString).openConnection();
				HttpURLConnectionInit(connection);
				inputStream = connection.getInputStream();
				long totle = connection.getContentLength();

				byte[] buffer = new byte[4 * 1024];
				int count = 0;
				int readLong = 0;
				int progress = 0;

				while ((readLong = inputStream.read(buffer)) != -1)
				{
					randomAccessFile.write(buffer, 0, readLong);
					count = count + readLong;

					if (100 * count / totle >= 100
							|| (100 * count / totle > progress + 3))
					{
						progress = (int) (100 * count / totle);
						UpdateNotification(NOTIFICATION_ID, notification, progress, FILE_NAME);
					}
				}

				return FileUtil.DOWNLOAD_SUCCESS;
			}
			catch (Exception e)
			{
				System.out.println(TAG + " Exception:" + e);
				failed(NOTIFICATION_ID, notification);
				return FileUtil.DOWNLOAD_SUCCESS;
			}
			finally
			{
				if (inputStream != null)
				{
					try {
						inputStream.close();
					}
					catch (Exception e2) {
					}
				}

				if (randomAccessFile != null)
				{
					try {
						randomAccessFile.close();
					}
					catch (Exception e2) {
					}
				}
			}

		}

		/**
		 * 为HttpURLConnection添加头部信息
		 */
		private void HttpURLConnectionInit(HttpURLConnection connection) throws ProtocolException {
			connection.setConnectTimeout(5 * 1000);
			connection.setRequestMethod("GET");
			connection.setRequestProperty("Accept",
					"image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
			connection.setRequestProperty("Charset", "UTF-8");
			connection.setRequestProperty("User-Agent",
					"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
			connection.setRequestProperty("Connection", "Keep-Alive");

			connection.setRequestProperty("Accept-Language", "en-us,en;q=0.7,zh-cn;q=0.3");
			connection.setRequestProperty("Accept-Encoding", "utf-8");
			connection.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
			connection.setRequestProperty("Keep-Alive", "300");
			connection.setRequestProperty("Accept-Language", "zh-CN");
		}

	}
}
